package www.wen.com.common.lib.util

import android.content.Context
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXTextObject
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import www.wen.com.common.BuildConfig.APPLICATION_ID
import www.wen.com.common.BuildConfig.WECHAT_APP_ID
import www.wen.com.common.lib.extension.toast


/**
 * @author WEN
 * @Description:
 * @date 2020/12/30 11:54
 */
object WxUtil {

    /**
     * 创建IWXAPI对象
     */
    fun getIWXAPI(context: Context): IWXAPI {
        val api = WXAPIFactory.createWXAPI(context, WECHAT_APP_ID, false)
        api.registerApp(WECHAT_APP_ID)
        return api
    }

    /**
     * 唤起微信登录
     */
    fun callWxLogin(api: IWXAPI) {
        val req = SendAuth.Req()
        req.scope =
            "snsapi_userinfo"   //snsapi_userinfo、snsapi_base  https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
        req.state = APPLICATION_ID
        api.sendReq(req)
    }

    /**
     * 微信分享文本
     */
    fun IWXAPI.shareText(shareText: String, isFriend: Boolean,action:((Boolean)->Unit)? = null):Boolean {

        if (!isWXAppInstalled) {
            toast("请安装微信")
            return false
        }

        val textObject = WXTextObject().apply { text = shareText }

        val isSend = sendReq(SendMessageToWX.Req().apply {
            message = WXMediaMessage().apply {
                mediaObject = textObject
                description = shareText
            }
            transaction = buildTransction("text")
            scene =
                if (isFriend) SendMessageToWX.Req.WXSceneTimeline else SendMessageToWX.Req.WXSceneSession
        })
        if(isSend){
            action?.invoke(isSend)
        }
        return isSend
    }

    private fun buildTransction(str: String?): String? {
        return if (str == null) System.currentTimeMillis()
            .toString() else str + System.currentTimeMillis()
    }


    /**
     * 调用微信支付
     * @param Mch_id
     * @param Nonce_str
     * @param Prepay_id
     */
    fun weChatPay(Mch_id: String?, Nonce_str: String?, Prepay_id: String?, iwxapi: IWXAPI) {
        if (!iwxapi.isWXAppInstalled) {
//            ToastUtils.showShort("您还未安装微信客户端")
            return
        }
        val payReq = PayReq()
        payReq.appId = WECHAT_APP_ID
        payReq.partnerId = Mch_id
        payReq.nonceStr = Nonce_str
        payReq.prepayId = Prepay_id
        payReq.timeStamp = (System.currentTimeMillis() / 1000).toString()
        payReq.packageValue = "Sign=WXPay"
        val stringBuilder = StringBuilder()
        stringBuilder.append("appid=" + payReq.appId)
        stringBuilder.append("&noncestr=" + payReq.nonceStr)
        stringBuilder.append("&package=" + payReq.packageValue)
        stringBuilder.append("&partnerid=" + payReq.partnerId)
        stringBuilder.append("&prepayid=" + payReq.prepayId)
        stringBuilder.append("&timestamp=" + payReq.timeStamp)
//        val stringSignTemp = stringBuilder.toString() + "&key=" + Constants.SECRET_KEY
//        payReq.sign = MD5.getMessageDigest(stringSignTemp.toByteArray()).toUpperCase()
        iwxapi.sendReq(payReq)
    }
}